package service

import (
	"github.com/leanote/leanote/app/db"
	"gopkg.in/mgo.v2/bson"
	"github.com/leanote/leanote/app/info"
	"log"
)

type CityService struct {
}

func (c CityService)Provinces() []info.Province  {
	var ps []info.Province
	db.Provinces.Find(bson.M{}).All(&ps)
	return ps
}

func (c CityService)Cities()[]info.City  {
	var cities []info.City
	db.Cities.Find(bson.M{}).All(&cities)
	return cities
}

func (c CityService)Districts()[]info.District  {

	var districts []info.District
	db.Districts.Find(bson.M{}).All(&districts)
	return districts
}

func (c CityService)FindProvinceById(id int) info.Province {
	var province info.Province
	db.GetByQ(db.Provinces,bson.M{"id":id},&province)
	return province
}

func (c CityService)FindCityById(id int)info.City  {
	var city info.City
	db.GetByQ(db.Cities,bson.M{"id":id},&city)
	return city
}

func (c CityService)FindDistrictById(id int)info.District  {
	var district info.District
	db.GetByQ(db.Districts,bson.M{"id":id},&district)
	return district
}

//查询省市区
func (c CityService)FindAddress(provinceId,cityId,districtId int) string {

	province:=c.FindProvinceById(provinceId)
	city:=c.FindCityById(cityId)
	district:=c.FindDistrictById(districtId)

	return province.Name+" "+city.Name+" "+district.Name
}

//通过区Id即可查询省市区
func (c CityService)FindAddressByDistrictId(districtId int) string {

	district:=c.FindDistrictById(districtId)
	city:=c.FindCityById(district.CityId)
	province:=c.FindProvinceById(city.ProvinceId)

	return province.Name+" "+city.Name+" "+district.Name
}

//热门城市
func (c CityService)Hots()[]info.City  {

	var hots []info.City
	db.ListByQ(db.Cities,bson.M{"hot":true},&hots)
	return hots
}

func (c CityService) InitCities()  {
	if !isNeedInitData() {
		log.Println("省市区数据已经添加")
		return
	}

	//初始化省市区

	ps := info.GetProvinces()
	for _, p := range ps {
		db.Insert(db.Provinces, p)
	}

	cs := info.GetCities()
	for _, c := range cs {
		db.Insert(db.Cities, c)
	}

	ds := info.GetDistricts()
	for _, d := range ds {
		db.Insert(db.Districts,d)
	}
}

//是否需要插入省市区数据
//如果省已有数据，则不添加
func isNeedInitData() bool {
	count,err:=db.Provinces.Count()
	if err !=nil {
		return false

	}
	return count == 0
}